<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <div style="width:100px">菜单名称：</div>
            <!-- <el-input v-model="input" placeholder="请输入菜单名称"></el-input> -->
            <i slot="label" class="el-icon-search" style="font-size:20px"></i>
            <el-select
              v-model="value"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入菜单名称"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary">查询</el-button>
            <el-button>重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表单 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>

      <el-table
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        :header-cell-style="{background:'#eee'}"
        border
        :default-expand-all="false"
        v-loading="loading"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="root_name" label="名称"></el-table-column>
        <el-table-column align="center" prop="permission" label="权限标志"></el-table-column>
        <el-table-column align="center" prop="sort" label="排序"></el-table-column>
        <el-table-column align="center" prop="add_time" label="创建时间"></el-table-column>
        <el-table-column align="center" prop="update_time" label="更新时间"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 右侧抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :label-position="labelPosition"
        label-width="100px"
        style="margin-left:50px"
        :model="formLabelAlign"
        :rules="rules"
      >
        <el-form-item label="父级菜单" prop="pid">
          <el-cascader
            v-model="formLabelAlign.pid"
            :options="optionsDraw"
            :show-all-levels="false"
            :props="{ checkStrictly: true,value:'id', label: 'root_name' }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="名称" prop="root_name">
          <el-input v-model="formLabelAlign.root_name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input
            v-model="formLabelAlign.permission"
            placeholder="请选输入权限标识"
            :disabled="title==='编辑'"
          ></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="sort">
          <el-input v-model="formLabelAlign.sort" placeholder="请输入优先级"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('form')">取消</el-button>
          <el-button type="primary" @click="submitForm('form')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getPageList, delPage, addPage, editPage } from "@/api/page";
import { parseTime } from "@/utils/index";

export default {
  name: "PagePermission",
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 表数据
      tableData: [],
      //select
      options: [],
      value: [],
      list: [],
      loading: false,
      states: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        "Colorado",
        "Connecticut",
        "Delaware",
        "Florida",
        "Georgia",
        "Hawaii",
        "Idaho",
        "Illinois",
        "Indiana",
        "Iowa",
        "Kansas",
        "Kentucky",
        "Louisiana",
        "Maine",
        "Maryland",
        "Massachusetts",
        "Michigan",
        "Minnesota",
        "Mississippi",
        "Missouri",
        "Montana",
        "Nebraska",
        "Nevada",
        "New Hampshire",
        "New Jersey",
        "New Mexico",
        "New York",
        "North Carolina",
        "North Dakota",
        "Ohio",
        "Oklahoma",
        "Oregon",
        "Pennsylvania",
        "Rhode Island",
        "South Carolina",
        "South Dakota",
        "Tennessee",
        "Texas",
        "Utah",
        "Vermont",
        "Virginia",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming"
      ],
      // 编辑抽屉
      drawer: false,
      direction: "rtl",
      title: "编辑",
      // 编辑表单
      labelPosition: "left",
      formLabelAlign: {
        pid: "",
        root_name: "",
        permission: "",
        sort: ""
      },
      rules: {
        pid: [{ required: true, message: "请选择父级", trigger: "blur" }],
        root_name: [
          { required: true, message: "请选输入菜单名", trigger: "blur" }
        ],
        permission: [
          { required: true, message: "请选输入权限标识", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请选输入排序", trigger: "blur" }]
      },
      optionsDraw: [
        {
          id: "0",
          root_name: "父级菜单"
        }
      ],
      loading: false
    };
  },
  mounted() {
    this.getPageList();
    this.list = this.states.map(item => {
      return { value: `value:${item}`, label: `label:${item}` };
    });
  },
  methods: {
    // 获取菜单树形
    async getPageList() {
      this.loading = true;
      const res = await getPageList({
        page: this.currentPage.toString(),
        limit: this.pageSize.toString()
      });
      this.loading = false;
      console.log(res);
      this.tableData = res.data;
      this.setTime(this.tableData);
      this.total = res.count;
      this.optionsDraw = [
        {
          id: "0",
          root_name: "父级菜单"
        }
      ];
      this.optionsDraw = this.optionsDraw.concat(res.data);
    },
    setTime(data) {
      data.forEach(item => {
        if (item.children) {
          this.setTime(item.children);
        }
        if (item.add_time == 0) {
          item.add_time = "-";
        } else {
          item.add_time = parseTime(item.add_time, "{y}-{m}-{d} {h}:{i}:{s}");
        }
        if (item.update_time == 0) {
          item.update_time = "-";
        } else {
          item.update_time = parseTime(
            item.update_time,
            "{y}-{m}-{d} {h}:{i}:{s}"
          );
        }
      });
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current;
      this.getPageList();
    },
    // select
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    //添加数据
    addList() {
      this.title = "添加";
      this.drawer = true;
    },
    // 每条数据
    async handleDel(row) {
      console.log(row);
      try {
        const res = await delPage({ id: row.id });
        console.log(res);
        this.getPageList();
        this.$message({
          message: "删除成功",
          type: "success"
        });
      } catch (error) {
        this.$message.error("删除失败");
        console.log(error);
      }
    },
    handleEdite(row) {
      const form = {
        pid: row.pid,
        root_name: row.root_name,
        permission: row.permission,
        sort: row.sort,
        id: row.id
      };
      this.formLabelAlign = form;
      this.drawer = true;
      this.title = "编辑";
    },
    // 编辑抽屉
    handleClose(done) {
      const form = {
        pid: "",
        root_name: "",
        permission: "",
        sort: ""
      };
      this.formLabelAlign = form;
      this.resetForm("form");
      done();
    },
    handleChange(value) {
      console.log(value);
      console.log(this.formLabelAlign);
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.title === "添加") {
            this.formLabelAlign.pid = this.formLabelAlign.pid[
              this.formLabelAlign.pid.length - 1
            ].toString();
            const res = await addPage({ ...this.formLabelAlign });
            if (res.st !== 1) {
              console.log(res);
              this.$message.error("添加失败");
            } else if (res.st === 1) {
              this.resetForm("form");
              const form = {
                pid: "",
                root_name: "",
                permission: "",
                sort: ""
              };
              this.formLabelAlign = form;
              this.getPageList();
              this.$message({
                message: "添加菜单成功",
                type: "success"
              });
              this.drawer = false;
            }
            this.resetForm("form");
          } else if (this.title === "编辑") {
            // this.formLabelAlign.pid = this.formLabelAlign.pid.join();
            const res = await editPage({ ...this.formLabelAlign });
            console.log(res);
            if (res.st !== 1) {
              console.log(res);
              this.$message.error("添加失败");
            } else if (res.st === 1) {
              this.resetForm("form");
              const form = {
                pid: "",
                root_name: "",
                permission: "",
                sort: ""
              };
              this.formLabelAlign = form;
              this.getPageList();
              this.$message({
                message: "编辑菜单成功",
                type: "success"
              });
              this.drawer = false;
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.drawer = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
</style>
